package com.hua.api.modules.express.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hua.api.core.constants.Status;
import com.hua.api.core.framework.util.exception.ApiError;
import com.hua.api.core.out.showapi.request.ShowApiExpressStatusQueryRequest;
import com.hua.api.core.out.showapi.request.ShowApiGetCompanyRequest;
import com.hua.api.core.out.showapi.request.ShowApiSetCallbackRequest;
import com.hua.api.core.properties.SysProperties;
import com.hua.api.core.util.StringUtil;
import com.hua.api.core.util.ValidationUtil;
import com.hua.api.modules.express.dao.ExpressOrderDao;
import com.hua.api.modules.express.service.ExpressOrderService;
import com.hua.api.modules.express.service.dto.ExpressOrderDto;
import com.hua.api.modules.express.util.ExpressOrderUtil;
import com.hua.api.modules.order.dao.OrderInfoDao;
import com.hua.api.modules.express.domain.ExpressOrder;
import com.hua.api.modules.order.domain.OrderInfo;
import com.hua.api.modules.order.domain.ShopInfo;
import com.hua.api.modules.order.service.OrderInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@SuppressWarnings("all")
@Slf4j
@Service("expressOrderService")
@RequiredArgsConstructor
public class ExpressOrderServiceImpl implements ExpressOrderService {

    private final OrderInfoDao orderInfoDao;

    private final ExpressOrderDao expressOrderDao;

    private final SysProperties sysProperties;

    private final OrderInfoService orderInfoService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void showApiNotify(String expressOrderNo) {
        log.info("【物流单状态回调】ExpressOrderServiceImpl.showApiNotify={} 收到物流信息回调",expressOrderNo);
        ExpressOrder expressOrder = expressOrderDao.findByExpressOrderNo(expressOrderNo);
        ValidationUtil.requireNotNull(expressOrder,"物流单不存在！");
        OrderInfo orderInfo = orderInfoDao.getObject(OrderInfo.class,expressOrder.getOrderId());
        ValidationUtil.requireNotNull(orderInfo,"订单信息不存在！");

        String toMobile = expressOrder.getToMobile();
        String phone = "";
        // 手机尾号后四位
        if(!StringUtil.isEmpty(toMobile) && toMobile.length()>4){
            phone = toMobile.substring(toMobile.length()-4);
        }

        log.info("ExpressOrderServiceImpl.showApiNotify phone={}",phone);
        ShowApiExpressStatusQueryRequest queryRequest = new ShowApiExpressStatusQueryRequest();
        queryRequest.setNu(expressOrder.getExpressOrderNo());
        queryRequest.setCom(expressOrder.getExpressCode());
        queryRequest.setPhone(phone);
        JSONObject queryBody =  queryRequest.getShowApiResBody();
        Integer retCode = queryBody.getInteger("ret_code");
        // log.info("queryBody={}",queryBody.toJSONString());
        if(null==retCode || retCode<10){
            throw ApiError.Type.LOGIC_ERROR.toException(queryBody.getString("msg"));
        }

        expressOrder.setOrderStatus(retCode);
        expressOrder.setResBody(queryBody.toJSONString());
        orderInfoDao.updateObject(expressOrder);

        // 只有礼品的话修改订单状态
        if(ExpressOrderUtil.onlyLipin(orderInfo.getExpressType())){
            Status.ExpressStatus expressStatus = Status.ExpressStatus.fromValue(retCode);
            if(expressStatus== Status.ExpressStatus.s104){
                orderInfo.setLogisticsStatus(Status.LogisticsStatus.yisongda.getValue());
            }else {
                orderInfo.setLogisticsStatus(Status.LogisticsStatus.peisongzhong.getValue());
            }
            orderInfoDao.updateObject(orderInfo);
        }


    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void showApiexpressOrderCreate(String orderNo, ExpressOrderDto dto) {
        log.info("【物流单信息录入】ExpressOrderServiceImpl.expressOrderCreate orderNo={},expressOrderNo={} ",orderNo,dto.getExpressOrderNo());
        // System.out.println("expressOrderCreate="+dto.getExpressOrderNo());
        OrderInfo orderInfo = orderInfoDao.findOrderInfoWithOrderNo(orderNo);
        ValidationUtil.requireNotNull(orderInfo,"订单数据不存在！");
        Status.OrderStatus orderStatus = Status.OrderStatus.fromValue(orderInfo.getStatus());

        if(orderStatus!= Status.OrderStatus.yijiedan){
            throw ApiError.Type.LOGIC_ERROR.toException("订单状态不正确，无法录入物流单！");
        }

        Status.LogisticsStatus logisticsStatus = Status.LogisticsStatus.fromValue(orderInfo.getLogisticsStatus());
        if(logisticsStatus!= Status.LogisticsStatus.daipeisong){
            throw ApiError.Type.LOGIC_ERROR.toException("订单配送状态不正确，无法录入物流单！");
        }

        ValidationUtil.requireNotNull(dto.getExpressOrderNo(),"物流单号不能为空！");
        ShowApiGetCompanyRequest request = new ShowApiGetCompanyRequest();
        request.setNu(dto.getExpressOrderNo());

        JSONObject resBody =  request.getShowApiResBody();
        ValidationUtil.requireNotNull(resBody,"物流单号不存在！");
        JSONObject data = resBody.getJSONArray("data").getJSONObject(0);
        String com = data.getString("com");
        String comName = data.getString("com_name");

        ExpressOrder express = ExpressOrderUtil.getShopApiExpressOrder(com,comName,orderInfo);
        express.setExpressOrderNo(dto.getExpressOrderNo());
        express.setThirdOrderNo(dto.getExpressOrderNo());
        express.setExpressType(Status.ExpressType.lipin.getValue());

        ShowApiExpressStatusQueryRequest queryRequest = new ShowApiExpressStatusQueryRequest();
        queryRequest.setNu(dto.getExpressOrderNo());
        queryRequest.setCom(com);
        queryRequest.setPhone(dto.getPhone()); //
        JSONObject queryBody =  queryRequest.getShowApiResBody();
        Integer retCode = queryBody.getInteger("ret_code");

        log.info("queryBody={}",queryBody.toJSONString());
        if(null==retCode || retCode<10){
            throw ApiError.Type.LOGIC_ERROR.toException(queryBody.getString("msg"));
        }

        express.setOrderStatus(retCode);
        express.setResBody(queryBody.toJSONString());
        orderInfoDao.saveObject(express);

        // 只有礼品的话修改订单状态
        if(ExpressOrderUtil.onlyLipin(orderInfo.getExpressType())){
            Status.ExpressStatus expressStatus = Status.ExpressStatus.fromValue(retCode);
            if(expressStatus== Status.ExpressStatus.s104){
                orderInfo.setLogisticsStatus(Status.LogisticsStatus.yisongda.getValue());
            }else {
                orderInfo.setLogisticsStatus(Status.LogisticsStatus.peisongzhong.getValue());
            }
            orderInfoDao.updateObject(orderInfo);
        }

        ShowApiSetCallbackRequest callbackRequest = new ShowApiSetCallbackRequest();
        callbackRequest.setNu(dto.getExpressOrderNo());
        callbackRequest.setCom(com);
        callbackRequest.setCallback_url(sysProperties.apiHost+"/api/expressOrder/showapi/notify/"+dto.getExpressOrderNo());
        callbackRequest.doRequest();

    }

    // 配送单自配送录入

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createSelfExpressOrder(String orderNo, ExpressOrderDto dto, Integer userId) {
        log.info("【物流单信息录入】ExpressOrderServiceImpl.createSelfExpressOrder orderNo={} ",orderNo);
        //
        OrderInfo orderInfo = orderInfoDao.findOrderInfoWithOrderNo(orderNo);
        ValidationUtil.requireNotNull(orderInfo,"订单数据不存在！");
        Status.OrderStatus orderStatus = Status.OrderStatus.fromValue(orderInfo.getStatus());


        if(orderStatus!= Status.OrderStatus.yijiedan ){
            throw ApiError.Type.LOGIC_ERROR.toException("订单状态不正确，无法录入物流单！");
        }

        Status.LogisticsStatus logisticsStatus = Status.LogisticsStatus.fromValue(orderInfo.getLogisticsStatus());

        if(logisticsStatus!= Status.LogisticsStatus.daipeisong && logisticsStatus != Status.LogisticsStatus.yiquxiao){
            throw ApiError.Type.LOGIC_ERROR.toException("订单配送状态不正确，无法录入物流单！");
        }

        ShopInfo shopInfo = orderInfoDao.getObject(ShopInfo.class, orderInfo.getShopId());
        ValidationUtil.requireNotNull(shopInfo,"订单数据不存在！");
        if(!StringUtil.equals(userId,shopInfo.getUserId())){
            throw ApiError.Type.LOGIC_ERROR.toException("无操作权限！");
        }

        ExpressOrder express = ExpressOrderUtil.getSelfExpressOrder(Status.ExpressCode.huayt.getValue(),Status.ExpressCode.huayt.getName(),orderInfo,shopInfo);
        String expressOrderNo = "211"+userId+orderInfo.getId()+StringUtil.createId(6);
        express.setExpressOrderNo(expressOrderNo);
        express.setThirdOrderNo(expressOrderNo);
        express.setExpressType(Status.ExpressType.xianhua.getValue());
        express.setOrderStatus(Status.LogisticsStatus.yisongda.getValue());
        express.setCourierMobile(dto.getCourierMobile());
        express.setCourierName(dto.getCourierName());
        orderInfoDao.saveObject(express);

        orderInfo.setShipperPhone(dto.getCourierMobile());
        orderInfo.setShipperName(dto.getCourierName());
        orderInfo.setLogisticsStatus(Status.LogisticsStatus.yisongda.getValue());
        orderInfoDao.updateObject(orderInfo);

    }
}
